package com.purong.purong.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.purong.purong.Contant;
import com.purong.purong.R;
import com.purong.purong.activity.ArticleDetActivity;
import com.purong.purong.adapter.ArticleListAdapter;
import com.purong.purong.bean.ArticleBean;
import com.purong.purong.bean.ArticleHeadBean;
import com.purong.purong.bean.ArticleListBean;
import com.purong.purong.util.CommonUtil;
import com.purong.purong.widget.LoadingView;
import com.yao.sdk.glide.GlideUtil;
import com.yao.sdk.net.ResponseInfo;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrCustomHandler;
import in.srain.cube.views.ptr.PtrDefaultCustomHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrPuRongLayout;

/**
 * Created by wenjiezeng on 2017/11/8.
 */
public class ArticleListFragment extends BaseFragment {

    private String catId;
    private RecyclerView recyclerView;
    private PtrPuRongLayout mPtrFrame;
    private ArticleListAdapter mAdapter;
    private List<ArticleBean> articleList=new ArrayList<>();
    private View headView;
    private ConvenientBanner cb;
    private LoadingView loadingView;
    private TextView cbTitle,cbCount;
    private ArticleHeadBean headBean;
    private ArticleListBean listBean;
    private int page=1;
    @Override
    public int getRootViewId() {
        return R.layout.fragment_article_list;
    }

    @Override
    public void initBundle() {
        catId=getArguments().getString("CAT_ID");
        if (catId==null)
            catId="";
    }

    @Override
    public void onPause() {
        super.onPause();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                if (mPtrFrame!=null&&mPtrFrame.isRefreshing()) {
                    mPtrFrame.refreshComplete();
                }
            }
        }, 100);
    }

    @Override
    public void initView(View rootView) {
        loadingView=(LoadingView)rootView.findViewById(R.id.loading_view);
        loadingView.setNoResultToast("暂无相关资讯","刷新");
        loadingView.setLoadListener(new LoadingView.OnLoadListener() {
            @Override
            public void onReload() {
                if (catId.equals("-1")){
                    getHeadArticle();
                }else {
                    getArticle(true);
                }
            }

            @Override
            public void onRefresh() {
                if (catId.equals("-1")){
                    getHeadArticle();
                }else {
                    getArticle(true);
                }
            }
        });
        recyclerView=(RecyclerView)rootView.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
        mAdapter=new ArticleListAdapter(getActivity());
        if (catId.equals("-1")){
            headView= LayoutInflater.from(getContext()).inflate(R.layout.info_list_head,null);
            cb= (ConvenientBanner) headView.findViewById(R.id.convenient_banner);
            headView.findViewById(R.id.main_lay).setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int)(CommonUtil.getScreenWidth(getActivity())/1.785)));
            cbTitle=(TextView)headView.findViewById(R.id.title);
            cbCount=(TextView)headView.findViewById(R.id.count);
            mAdapter.addHead(headView);
        }
        mAdapter.setData(articleList);
        mAdapter.setOnInfoItemClickListener(new ArticleListAdapter.OnArticleItemClickListener() {
            @Override
            public void onArticleClick(ArticleBean bean) {
                Intent intent=new Intent(getActivity(), ArticleDetActivity.class);
                intent.putExtra("ARTICLE_ID",bean.getArticle_id());
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(mAdapter);
        mPtrFrame = (PtrPuRongLayout) rootView.findViewById(R.id.rotate_header_list_view_frame);
        mPtrFrame.setPtrHandler(new PtrCustomHandler() {
            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                if (articleList.size() == 0) {
                    return false;
                } else {
                    return PtrDefaultCustomHandler.checkContentCanBePulledUp(frame, content, footer);
                }

            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                getArticle(false);

            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (catId.equals("-1")){
                    getHeadArticle();
                }else {
                    getArticle(true);
                }
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultCustomHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
        // the following are default settings
        mPtrFrame.setRatioOfHeaderHeightToRefresh(1.0f);
    }
    private void getHeadArticle(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        if (!request(Contant.ARTICLE_HEAD, params, true, false)) {
            if (!hasDestroy())
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        if (mPtrFrame.isRefreshing()) {
                            mPtrFrame.refreshComplete();
                        }
                    }
                }, 100);
        }

    }
    private void getArticle(boolean clear){
        Map<String, String> params = new LinkedHashMap<String, String>();
        if (catId.equals("-1")&&headBean!=null&&headBean.getArticle_head()!=null&&headBean.getArticle_head().size()>0){
            StringBuffer buffer=new StringBuffer();
            for (int i = 0; i <headBean.getArticle_head().size() ; i++) {
                buffer.append(headBean.getArticle_head().get(i).getArticle_id());
                if (i!=headBean.getArticle_head().size()-1)
                buffer.append(",");
            }
            params.put("article_head",buffer.toString());
            Log.e("zwj","....head_id="+buffer.toString());
        }
        params.put("category_id",catId.equals("-1")?"":catId);
        if (clear){
            page=1;
            if (articleList.size()==0){
                if (catId.equals("-1")){
                    if (headBean==null||headBean.getArticle_head()==null||headBean.getArticle_head().size()==0)
                    loadingView.loading();
                }else {
                    loadingView.loading();
                }
            }


//            articleList.clear();
//            mAdapter.notifyDataSetChanged();

        }
        Log.e("zwj","..page="+page);
        params.put("page",page+"");
        if (!request(Contant.ARTICLE_LIST, params, true)) {
            if (!hasDestroy())
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        if (mPtrFrame.isRefreshing()) {
                            mPtrFrame.refreshComplete();
                        }
                    }
                }, 100);
            if (articleList.size()==0){
                if (catId.equals("-1")){
                    if (headBean==null||headBean.getArticle_head()==null||headBean.getArticle_head().size()==0)
                        loadingView.fail();
                }else {
                    loadingView.fail();
                }
            }
        }
    }
    private void setHeadArticle() {
        cbTitle.setText(headBean.getArticle_head().get(0).getTitle());
        cbCount.setText("1/"+headBean.getArticle_head().size());
        cb.setPages(new CBViewHolderCreator<ImageViewHolder>() {
            @Override
            public ImageViewHolder createHolder() {
                return new ImageViewHolder();
            }
        }, headBean.getArticle_head());
        cb.startTurning(3000);
        cb.setCanLoop(true);
        cb.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                cbTitle.setText(headBean.getArticle_head().get(position).getTitle());
                cbCount.setText((position+1)+"/"+headBean.getArticle_head().size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        cb.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent=new Intent(getActivity(), ArticleDetActivity.class);
                intent.putExtra("ARTICLE_ID",headBean.getArticle_head().get(position).getArticle_id());
                startActivity(intent);
            }
        });


    }
    @Override
    public void initData() {
        if (catId.equals("-1")){
            getHeadArticle();
        }else {
            getArticle(true);
        }

    }


    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy()){
            return;
        }
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.ARTICLE_HEAD)){
            if (responseInfo.isRequestOk){
                try{
                    headBean= JSON.parseObject(responseInfo.content,ArticleHeadBean.class);
                    if (headBean!=null&&headBean.getArticle_head()!=null&&headBean.getArticle_head().size()>0){
                        headView.setVisibility(View.VISIBLE);
                        setHeadArticle();
                    }else {
                        headView.setVisibility(View.GONE);
                    }

                    getArticle(true);
                }catch (Exception e){

                }
            }else {
                if (mPtrFrame.isRefreshing()) {
                    mPtrFrame.refreshComplete();
                }
            }
        }else if (responseInfo.url.equals(Contant.ARTICLE_LIST)){
            if (mPtrFrame.isRefreshing()) {
                mPtrFrame.refreshComplete();
            }
            if (responseInfo.isRequestOk){
                try{
                    listBean=JSON.parseObject(responseInfo.content,ArticleListBean.class);
                    if (responseInfo.params.get("page").equals("1")){
                        articleList.clear();
                    }
                    if (listBean!=null&&listBean.getArticle_list()!=null){
                        if (listBean.getArticle_list().size()>0)
                            page++;

                        articleList.addAll(listBean.getArticle_list());
                    }
                    mAdapter.notifyDataSetChanged();
                    if (catId.equals("-1")){
                        if (headView.getVisibility()==View.GONE&&articleList.size()==0){
                            loadingView.noResultWithRefresh();
                        }else {
                            loadingView.finish();
                        }
                    }else if (articleList.size()==0){
                        loadingView.noResultWithRefresh();
                    }else {
                        loadingView.finish();
                    }

                }catch (Exception e){
                    if (page==1)
                        loadingView.fail();
                }
            }else {
                if (page==1)
                    loadingView.fail();
            }

        }
    }

    public class ImageViewHolder implements Holder<ArticleBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, ArticleBean data) {
            GlideUtil.getInstance().load(getActivity(), data.getMaster_url(), imageView, true);
        }
    }
    public void scroll2Top(){
        if (recyclerView!=null&&articleList!=null){
            recyclerView.scrollToPosition(0);
        }

    }
}
